import urlConfig from './config.js'
export const request = (url, method, data, header = {}) => {
  function clearState () {
    uni.removeStorageSync('user_info')
    uni.redirectTo({
      url: '/pages/index/login'
    });
  }
  const token = uni.getStorageSync('token');
  const isLogin = getCurrentPages()[0].route.includes("login")
  if (!token && !isLogin) {
    return clearState()
  }
  if (token) {
    header['Token'] = token;
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: urlConfig + '/' + url,
      method,
      data: data,
      dataType: 'json',
      header: header,
      success: function (res) {
        if (res.data.ErrorCode === 'nologin') {
          uni.showToast({
            title: res.data.Message,
            duration: 2000,
            icon: "error"
          });
          setTimeout(() => {
            clearState()
          }, 1000)
        }
        resolve(res.data)
      },
      error: function (parmas) {
        reject(parmas)
      }
    })
  })
}